import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:meeting_note/deepseek/config.dart';

class StreamingChunk {
  final String type; // "reasoning" or "content"
  final String data;

  StreamingChunk({required this.type, required this.data});

  @override
  String toString() => jsonEncode({'type': type, 'data': data});
}

class DeepSeekClient {
  final String apiKey = DsConfig.secretKey;
  final String apiUrl = DsConfig.apiUrl;
  final String referer = DsConfig.referer;
  final String title = DsConfig.title;

  DeepSeekClient();

  Stream<StreamingChunk> streamChatCompletions({
    required List<Map<String, String>> messages,
    String model = "deepseek/deepseek-r1-0528:free",
    double temperature = 0.01,
    int maxTokens = 16*1024,
  }) async* {
    final headers = {
      'Authorization': 'Bearer $apiKey',
      'Content-Type': 'application/json',
      'HTTP-Referer': referer,
      'X-Title': title,
    };

    final body = jsonEncode({
      "model": model,
      "messages": messages,
      "temperature": temperature,
      "max_tokens": maxTokens,
      "stream": true,
    });

    final request = http.Request('POST', Uri.parse(apiUrl))
      ..headers.addAll(headers)
      ..body = body;

    final response = await request.send();

    if (response.statusCode != 200) {
      throw Exception('DeepSeek API error: ${response.statusCode}');
    }

    final stream = response.stream
        .transform(utf8.decoder)
        .transform(const LineSplitter());

    await for (final line in stream) {
      if (line.startsWith('data:')) {
        final data = line.substring(5).trim();
        if (data == '[DONE]') break;
        try {
          final jsonData = jsonDecode(data);
          final delta = jsonData['choices']?[0]?['delta'];
          if (delta == null) continue;
          final reasoning = delta['reasoning'];
          if (reasoning != null && reasoning.toString().isNotEmpty) {
            yield StreamingChunk(type: 'reasoning', data: reasoning.toString());
          }
          final content = delta['content'];
          if (content != null && content.toString().isNotEmpty) {
            yield StreamingChunk(type: 'content', data: content.toString());
          }
        } catch (_) {
          // Ignore malformed lines
        }
      }
    }
  }
}

// DeepSeekClient 封装了 DeepSeek API 的流式调用，streamChatCompletions 方法支持流式输出。
// 使用 http.Request 发送 POST 请求，解析 SSE 响应，遇到 data: 行时解析 JSON 并 yield 内容。
// 错误处理简单，遇到格式不符的行直接忽略。
